package com.atguigu.tingshu.search.listener;

import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.search.service.impl.ItemServiceImpl;
import org.redisson.api.RBloomFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplicationRunListener;
import org.springframework.context.ConfigurableApplicationContext;

import java.time.Duration;
import java.util.List;

/**
 * @author baosi
 * @date 2025/3/25
 * @description 利用springBoot的监听器机制完成对分布式布隆数据的同步
 * @credit 2025
 */
public class BloomFilterListener implements SpringApplicationRunListener {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
      * @description: 该方法springboot在启动过程中回调(包含了spring中定义的bean对象创建完毕) 需要使用spi机制将Listener放入
      * @author: baosi
      * @date: 2025/3/27 9:46
      */
    @Override
    public void started(ConfigurableApplicationContext context, Duration timeTaken) {
        boolean containsBean = context.containsBean("rBloomFilter");
        if (containsBean) {
            // 1.从spring容器中获取到布隆过滤器的Bean对象
            RBloomFilter rBloomFilter = context.getBean("rBloomFilter", RBloomFilter.class);
            if (rBloomFilter.count() == 0) {
                // 2.从spring容器中获取应用的Bean对象
                ItemServiceImpl itemServiceImpl = context.getBean("itemServiceImpl", ItemServiceImpl.class);
                // 3.获取数据
                List<Long> albumInfoIdList = itemServiceImpl.getAlbumInfoIdList();
                // 4.将数据放到布隆过滤器中
                for (Long albumId : albumInfoIdList) {
                    rBloomFilter.add(albumId);
                }
            }
            // 5.布隆过滤器元素是否同步进去
            logger.info("分布式布隆过滤器的元素个数：" + rBloomFilter.count());
        }
    }
}
